package com.liao.tensquare.advice;

import com.liao.tensquare.entity.Result;
import com.liao.tensquare.entity.StatusCode;
import com.liao.tensquare.exception.PreAuthorizeException;
import com.liao.tensquare.exception.RecordException;
import com.liao.tensquare.exception.UserRegisteredException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@ControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result exception(Exception e, HttpServletResponse response) {
        Class<? extends Exception> aClass = e.getClass();
        String typeName = aClass.getTypeName();
        log.info("Exception->{}",typeName);
        log.info("Exception->{}",e.getMessage());
        e.printStackTrace();
        if (e instanceof UserRegisteredException) {
            return new Result(false, e.getMessage(), StatusCode.USERREGISTERED);
        }
        if (e instanceof RecordException) {
            return new Result(false, e.getMessage(), StatusCode.PARAMS_IN_ERROR);
        }
        if (e instanceof PreAuthorizeException){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
        return new Result(false, e.getMessage(), StatusCode.ERROR);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e){
        log.info("MethodArgumentNotValidException->{}",e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuilder message = new StringBuilder();
        for (int i = 0; i < fieldErrors.size(); i++) {
            String str;
            if (i == fieldErrors.size() - 1){
                str = fieldErrors.get(i).getDefaultMessage();
            }else {
                str = fieldErrors.get(i).getDefaultMessage() + ",";
            }
            message.append(str);
        }
        return new Result(false, message.toString(),StatusCode.PARAMS_IN_ERROR);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public Result noHandlerFoundException(NoHandlerFoundException e, HttpServletRequest request){
        System.out.println("==================");
        Integer attribute = (Integer) request.getAttribute("javax.servlet.error.status_code");
        request.setAttribute("javax.servlet.error.status_code",404);
        return new Result(false,"url未找到",StatusCode.URL_NOTFOUND);
    }

}
